import React, { useEffect, useState } from 'react';

import ReactECharts from 'echarts-for-react';
import { Avatar, Card, List, message, Input } from 'antd';
import { listChartByPageUsingPost } from '@/services/gekbi/chartController';
import { useModel } from '@@/exports';
import type { SearchProps } from 'antd/es/input/Search';
const { Search } = Input;
const ListChart: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 3,
    sortField: 'createTime',
    sortOrder: 'desc',
  };
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const { userAvatar } = initialState?.currentUser;

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listChartByPageUsingPost(searchParams);
      if (res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取数据失败');
      }
    } catch (e: any) {
      message.error('获取数据失败' + e.message);
    }
    setLoading(false);
  };
  // 搜索方法
  const onSearch: SearchProps['onSearch'] = (value) => {
    setSearchParams({
      ...initSearchParams,
      name: value,
    });
  };
  // 初始化数据，搜索参数改变会重新执行loadData
  useEffect(() => {
    loadData();
  }, [searchParams]);
  return (
    <div className="list">
      <Search
        placeholder="请搜索图表"
        enterButton="搜索"
        size="large"
        loading={loading}
        onSearch={onSearch}
      />
      <div style={{ marginBottom: 16 }}></div>
      <List
        itemLayout="vertical"
        size="large"
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize: pageSize,
            });
          },
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total: total,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item
            key={item.name}
            extra={
              <Card>
                <ReactECharts option={JSON.parse(item.genChart)} style={{ width: '272px' }} />
              </Card>
            }
          >
            <List.Item.Meta
              avatar={<Avatar src={userAvatar && userAvatar} />}
              title={item.name}
              description={item.chartType ? '图表类型:' + item.chartType : ''}
            />
            {item.genResult}
          </List.Item>
        )}
      />
    </div>
  );
};
export default ListChart;
